import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:wanxiang_app/bean/platform_entity.dart';
import '../../bean/anchor_entity.dart';
import '../../utils/network_manager.dart';
import '../../utils/network_url.dart';
import '../../utils/toast_util.dart';
import '../../widgets/myappbar.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:get/get.dart';
import 'package:url_launcher/url_launcher.dart';
import '../../widgets/simple_dialog.dart';

class LiveController extends GetxController{
   EasyRefreshController easyRefreshController = EasyRefreshController(
    controlFinishRefresh: false,
    controlFinishLoad: true,
  );
  @override
  void onInit() {
    super.onInit();

    _listData();
  }
  @override
  void onClose() {
    super.onClose();
  }
  List<AnchorData> anchorList = [];

  void _getAnchorListData(){
    DioManager.getInstance().post(ServiceUrl.anchorList, {
      'top':'0',
      'platformcode':platformData.platformcode
    }, (data) async {
      AnchorEntity bannerEntity = AnchorEntity.fromJson(jsonDecode(data));
      anchorList = bannerEntity.data;
      update();
    }, (error) {
      ToastUtil.show(error);
    });
  }

  List<PlatformData> platformList = [];
  late PlatformData platformData;
  void _listData(){
    DioManager.getInstance().post(ServiceUrl.livePlatForm, null, (data) async {
      PlatformEntity bannerEntity = PlatformEntity.fromJson(jsonDecode(data));
      platformList = bannerEntity.data;
      PlatformData mm = PlatformData();
      mm.platform='全部';
      mm.platformcode='';
      platformList.insert(0, mm);
      platformData = platformList[0];
      _getAnchorListData();
      update();
    }, (error) {
      ToastUtil.show(error);
    });
  }
}


class LivePage extends  GetView<LiveController>  {

  late LiveController controller ;
  late BuildContext context ;

  @override
  Widget build(BuildContext context1) {
    Get.lazyPut<LiveController>(() => LiveController());
    controller = Get.find();
    context = context1;

    return GetBuilder<LiveController>(
      builder: (_){
        return  Scaffold(
            appBar: MyAppBar(context: context, title: '合作主播',hasLeading: true,),
            backgroundColor: Colors.white,
            body:_content());
      },
    );
  }

  Widget _content(){
    return Container(
      child: Column(
        children: [
          _gameNamesList(),
          Container(
            height: MediaQuery.of(context).size.height - 130.h,
            child:   _refresh()
          ),
        ],
      ),
    );
  }
  Widget _refresh(){
    return Scaffold(
      body:  EasyRefresh(
        header: ClassicHeader(
          dragText: 'Pull to refresh'.tr,
          armedText: 'Release ready'.tr,
          readyText: 'Refreshing...'.tr,
          processingText: 'Refreshing...'.tr,
          processedText: 'Succeeded'.tr,
          noMoreText: 'No more'.tr,
          failedText: 'Failed'.tr,
          messageText: 'Last updated at %T'.tr,
        ),
        footer: ClassicFooter(
          dragText: 'Pull to load'.tr,
          armedText: 'Release ready'.tr,
          readyText: 'Loading...'.tr,
          processingText: 'Loading...'.tr,
          processedText: 'Succeeded'.tr,
          noMoreText: 'No more'.tr,
          failedText: 'Failed'.tr,
          messageText: 'Last updated at %T'.tr,
        ),
        onRefresh: () async {
        },
        onLoad: () async {
        },
        child: ListView.separated(
          itemBuilder: (context, index) {
            return _gameItems(index);
          },
          separatorBuilder: (context, index) =>
          Container(
            height: 2.h,
            decoration: const BoxDecoration(
              color: Color(0xFFF7F8FC),
            ),
          ),
          itemCount: controller.anchorList.length,
        ),
      )
    );
  }

  Widget _gameNamesList(){
    return
      Container(
          margin: EdgeInsets.fromLTRB(16.w, 16.h, 16.w, 0),
          child: SingleChildScrollView(
            scrollDirection:Axis.horizontal,
            child: Row(
              children: _gameNameListItems(),
            ),
          )
      )
    ;
  }

  List<Widget> _gameNameListItems(){
    List<Widget> items = [];
    for(int i=0;i<controller.platformList.length;i++){
      items.add(_gameNameItems(controller.platformList[i],i));
    }

    return items;
  }
  Widget _gameNameItems(PlatformData item,index){
    return InkWell(
      onTap: (){
        controller.platformData = item;
        controller._getAnchorListData();
        controller.update();
      },
      child: Container(
        alignment: Alignment.center,
        height: 30.h,
        padding: EdgeInsets.fromLTRB(12.w, 0, 12.w, 0),
        margin: EdgeInsets.only(right: 10.w),
        decoration:   controller.platformData.platformcode==item.platformcode?
        BoxDecoration(
            borderRadius: BorderRadius.circular(10.r),
          color: const Color(0xFF007BE5)
        ):BoxDecoration(
            borderRadius: BorderRadius.circular(10.r),
            color: const Color(0xFFF7F8FC)
        ),
        child: Text(item.platform,style: TextStyle(color:  controller.platformData.platformcode==item.platformcode? Colors.white:const Color(0xFF333333),fontSize: 14.sp),),
      )
    ) ;
  }


  Widget _liveList(){
    return
      Container(
          margin: EdgeInsets.fromLTRB(16.w, 16.h, 16.w, 0),
          child: SingleChildScrollView(
            scrollDirection:Axis.horizontal,
            child: Row(
              children: _liveListItems(),
            ),
          )
      )
    ;
  }

  List<Widget> _liveListItems(){
    List<Widget> items = [];
    items.add(_liveItem());
    return items;
  }

  Widget _liveItem(){
    return Container(
      width: 142.w,
      height: 88.h,
      margin: EdgeInsets.only(right: 10.w),
      decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(10.r),
          color: Color(0xFF007BE5)
      ),
    );
  }

  Widget _gameItems(int index){
    return InkWell(
      onTap: (){
        showDialog(context: context, builder: (BuildContext context1) {
          return MySimpleDialog(callBack: (String content) {
            if(content == 'cancel'){
              Navigator.pop(context1);
            }else if(content == 'sure'){
              launchUrl(Uri.parse((controller.anchorList[index].openUrl)));
              Navigator.pop(context1);
            }
          },
            msg: "查看主播详情将跳转至第三方网站",
            sureText: "确定",
          );
        });
      },
      child: Container(
        decoration: BoxDecoration(
            color: Colors.white
        ),
        padding: EdgeInsets.only(left: 16.w,right: 13.w,top: 12.h,bottom: 13.h),
        child: Row(
          children: [
            Container(
              width: 142.w,
              height: 88.w,
              child: ClipRRect(
                  borderRadius: BorderRadius.circular(15.r),
                  child:   Image.network(controller.anchorList[index].imgUrl,width: 110.w,height: 82.h,fit:BoxFit.fitHeight ,)
              ),

            ),
            SizedBox(width: 14.w,),
            Container(
                width: MediaQuery.of(context).size.width - 29.w - 14.w - 100.w -43.w,
                child:  Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: [
                    SizedBox(height: 5.h,),
                    Text(controller.anchorList[index].anchorName,
                      style: TextStyle(color: Color(0xFF333333),fontSize: 14.sp,fontWeight: FontWeight.bold),maxLines: 1,    textAlign: TextAlign.left,
                      overflow: TextOverflow.ellipsis,),
                    SizedBox(height: 5.h,),
                    Text('直播平台：${controller.anchorList[index].platform}',style: TextStyle(color: Color(0xFF666666),fontSize: 13.sp),),
                    SizedBox(height: 5.h,),
                    Text('房间号/ID:${controller.anchorList[index].roomId}',style: TextStyle(color: Color(0xFF666666),fontSize: 13.sp),),
                  ],
                )
            )

          ],
        ),
      )
    ) ;
  }

}